import React, {forwardRef} from 'react';
import ReactDOM from 'react-dom';

interface Props {

}

interface InputProps {

}

const TextInput = React.forwardRef((props: InputProps, ref: React.Ref<HTMLInputElement>/*←这个就是函数组件接受到的ref*/) => {
  return <input type="text" ref={ref}/>
});

class Form extends React.Component<Props> {
  textInput: React.RefObject<HTMLInputElement>;

  constructor(props: Props) {
    super(props);
    this.textInput = React.createRef();
  }

  getFocus = () => {
    this.textInput.current!.value = new Date().toLocaleString();
    this.textInput.current!.focus();
  };

  render() {
    return (
      <>
        <TextInput
          ref={this.textInput}/> {/*←这里的ref会被转发(通过React.forwardRef方法)，转发给TextInput函数组件里的元素*/}
        <button onClick={this.getFocus}>获得焦点</button>
      </>
    )
  }
}


ReactDOM.render(<Form/>, document.getElementById('root'));
